package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/wechat_v3"
	"errors"
	"github.com/gin-gonic/gin"
	"strings"
)

var SeparateAccountsSub = new(separateAccountsSubService)

type separateAccountsSubService struct{}

func (s *separateAccountsSubService) Page(c *gin.Context, req model.ReqList) ([]model.SeparateAccountSubList, int64, error) {
	accountR, _ := Request.Account(c)
	// 分页
	list := make([]model.SeparateAccountSubList, 0)
	offset := (req.PageNo - 1) * req.PageSize
	query := orm.Db.Alias("a").Desc("a.id")
	query.Where("a.acid =?", accountR.Id)
	query.Join("LEFT", "separate_group", "separate_group.id=a.group_id")
	//判断子账户
	total, err := query.Limit(req.PageSize, offset).FindAndCount(&list)
	a := new(areaService)
	for i, v := range list {
		id, _ := a.InfoById(v.SeparateAccountsSub.Area, "mergename")
		if id != nil {
			array := strings.Split(id.Mergename, ",")
			list[i].ProvinceName = array[1]
			if len(array) > 2 {
				list[i].CityName = array[2]
			}
			if len(array) > 3 {
				list[i].AreaName = array[3]
			}
		}
		list[i].GroupName = v.Group.Name
	}
	if err != nil {
		return nil, 0, err
	}
	return list, total, nil
}

func (s *separateAccountsSubService) Save(c *gin.Context, req model.ReqSeparateAccountsSub) error {
	accountR, _ := Request.Account(c)
	if req.Type != "PERSONAL_OPENID" && req.Type != "MERCHANT_ID" {
		return errors.New("type参数错误，取值【PERSONAL_OPENID/MERCHANT_ID】")
	}
	if req.Type == "MERCHANT_ID" && req.FullName == "" {
		return errors.New("参数错误，type类型为子商户时【full_name】必填")
	}

	res, err := AccountSetting.InfoById(accountR.Id, "miniprogram")
	if err != nil {
		return err
	}
	account := wechat_v3.SeparateConfig
	account.AppId = gconv.String(res["app_id"])
	account.PayCertPath = gconv.String(res["pay_cert_path"])
	account.PayKeyFilePath = gconv.String(res["pay_cert_key_path"])
	account.PaySerialNo = gconv.String(res["pay_serial_no"])
	account.PayKeyV3 = gconv.String(res["pay_key_v3"])
	account.PayMchId = gconv.String(res["pay_mch_id"])
	account.PayKey = gconv.String(res["pay_key"])
	_, err = account.SubAccount(c, &model.ReqSubAccount{
		SubMchId:         req.SubMchId,
		ReceivierType:    req.Type,
		ReceivierAccount: req.Account,
		ReceivierName:    req.FullName,
	})
	if err != nil {
		return err
	}
	if req.Id > 0 {
		// 保存数据
		_, err = orm.Db.ID(req.Id).Where("acid =?", accountR.Id).Update(req)
		if err != nil {
			return err
		}
	} else {
		// 保存数据
		req.Acid = accountR.Id
		_, err = orm.Db.Insert(req)
		if err != nil {
			return err
		}
	}
	return nil
}
func (s *separateAccountsSubService) Del(c *gin.Context, req model.ReqId) error {
	accountR, _ := Request.Account(c)
	_, err := orm.Db.ID(req.Id).Where("acid =?", accountR.Id).Delete(new(tables.SeparateAccountsSub))
	if err != nil {
		return err
	}
	return nil
}

// 绑定用户
func (s *separateAccountsSubService) BindUser(c *gin.Context, req model.ReqSeparateAccountsSub) error {
	accountR, _ := Request.Account(c)
	if req.Type != "PERSONAL_OPENID" && req.Type != "MERCHANT_ID " {
		return errors.New("type参数错误，取值【PERSONAL_OPENID/MERCHANT_ID】")
	}
	if req.Type == "MERCHANT_ID" && req.FullName == "" {
		return errors.New("参数错误，type类型为子商户时【full_name】必填")
	}

	res, err := AccountSetting.InfoById(accountR.Id, "miniprogram")
	if err != nil {
		return err
	}
	account := wechat_v3.SeparateConfig
	account.AppId = gconv.String(res["app_id"])
	account.PayCertPath = gconv.String(res["pay_cert_path"])
	account.PayKeyFilePath = gconv.String(res["pay_cert_key_path"])
	account.PaySerialNo = gconv.String(res["pay_serial_no"])
	account.PayKeyV3 = gconv.String(res["pay_key_v3"])
	account.PayMchId = gconv.String(res["pay_mch_id"])
	account.PayKey = gconv.String(res["pay_key"])
	_, err = account.SubAccount(c, &model.ReqSubAccount{
		SubMchId:         req.SubMchId,
		ReceivierType:    req.Type,
		ReceivierAccount: req.Account,
		ReceivierName:    req.FullName,
	})
	if err != nil {
		return err
	}
	return nil
}

// 商户信息
func (s *separateAccountsSubService) ListBySubMchId(field string, subMchId string) (
	[]model.SeparateAccountSubList, error) {
	list := make([]model.SeparateAccountSubList, 0)
	query := orm.Db.Alias("a").Desc("a.id")
	query.Where("a.sub_mch_id =? and state = ?", subMchId, 1)
	query.Join("LEFT", "separate_group", "separate_group.id=a.group_id")
	//判断子账户
	err := query.Find(&list)
	if err != nil {
		return nil, err
	}
	return list, nil
}
